let Message = {}

// 处理messageElement消失后，其他提示向上移动
function transitionElement () {
  var messageDomList = document.getElementsByClassName('message-vue')
  for (let i = 0; i <= messageDomList.length; i++) {
    if (messageDomList[i]) {
      messageDomList[i].style.top = 20 + 64 * i + 'px'
    }
  }
}

Message.install = function (Vue, options) {
  // 初始化options
  let opts = {
    message: '', // 显示文字
    type: 'info', // 主题显示类型 success/warning/info/error
    duration: 2500 // 持续时间
  }
  // 合并初始参数opts和传入参数options
  for (let prop in options) {
    if (options.hasOwnProperty(prop)) {
      opts[prop] = options[prop]
    }
  }

  let messageCount = 0

  Vue.prototype.$message = (option) => {
    for (let prop in option) {
      if (option.hasOwnProperty(prop)) {
        opts[prop] = option[prop]
      }
    }
    console.log(opts)
    messageCount = document.getElementsByClassName('message-vue').length
    // 初始化dom
    let MessageDom = Vue.extend({
      template: `<div class="message-vue message-vue__${opts.type}" style="top:${20 + 64 * messageCount}px;z-index:200${messageCount + 1}"><span>${opts.message}</span>
        ${opts.duration === 0 ? '<div class="message-vue-close" @click="close">x</div>' : ''}
      </div>`,
      methods: {
        close () {
          console.log(this)
          document.body.removeChild(this.$el)
          transitionElement()
        }
      }
    })
    let MessageElement = new MessageDom().$mount().$el
    document.body.append(MessageElement)
    if (opts.duration > 0) {
      setTimeout(() => {
        document.body.removeChild(MessageElement)
        transitionElement()
      }, opts.duration)
    }
  }
}

export default Message
